package cc.idoone.spring_boot_hello.swagger;

import cc.idoone.spring_boot_hello.mybatis.h2.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hemj
 * @since 2017/10/20
 */
@Api(value = "/api/users", tags = {"用户模块"})
@RestController
@RequestMapping(value = "/api/users")
public class UserController {

	static Map<Integer, User> users = Collections.synchronizedMap(new HashMap<Integer, User>());

	@ApiOperation(value = "获取用户列表", notes = "获取所有用户列表")
	@GetMapping
	public List<User> getUserList() {
		List<User> r = new ArrayList<User>(users.values());
		return r;
	}

	@ApiOperation(value = "创建用户", notes = "根据User对象创建用户")
	@PostMapping
	public String postUser(
			@ApiParam(value = "用户详细实体user", required = true) @RequestBody User user) {
		users.put(user.getId(), user);
		return "success";
	}

	@ApiOperation(value = "获取用户详细信息", notes = "根据url的id来获取用户详细信息")
	@GetMapping("/{id}")
	public User getUser(
			@ApiParam(value = "用户ID", required = true, defaultValue = "1") @PathVariable Integer id) {
		return users.get(id);
	}

	@ApiOperation(value = "更新用户详细信息", notes = "根据url的id来指定更新对象，并根据传过来的user信息来更新用户详细信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path"),
			@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
	})
	@PutMapping("/{id}")
	public String putUser(@PathVariable Integer id, @RequestBody User user) {
		User u = users.get(id);
		if (u == null) {
			return "User not found";
		}
		u.setName(user.getName());
		u.setAge(user.getAge());
		users.put(id, u);
		return "success";
	}

	@ApiOperation(value = "删除用户", notes = "根据url的id来指定删除对象")
	@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path")
	@DeleteMapping("/{id}")
	public String deleteUser(@PathVariable Integer id) {
		users.remove(id);
		return "success";
	}

}
